package com.wufun.overseas.main.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.wufun.baselibrary.download.CommonDownloadFactory;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.utils.FileUtils;
import com.wufun.baselibrary.utils.LogUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.adapters.DownloadManagerAdapter;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.models.event.DownloadResultEvent;
import com.wufun.overseas.tools.DownloadManager;
import com.wufun.overseas.tools.MyDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by tangbl on 2017/12/7 0007.
 */

public class DownloadManagerActivity extends MyActivity implements DownloadManagerAdapter.AdapterInterface {

    @Bind(R.id.download_listview)
    ExpandableListView downloadListview;

    private DownloadManagerAdapter mAdapter;
    private List<List<DownLoadModel>> mDataMap = new ArrayList<>();
    private List<DownLoadModel> unPlayDataList = new ArrayList<>();
    private List<DownLoadModel> playDataList = new ArrayList<>();

    private static long lastClickTime = 0;
    private static long now = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_downloadmanager);
        ButterKnife.bind(this);
    }

    public static Intent buildIntent(Context context, String title) {
        Intent intent = new Intent(context, DownloadManagerActivity.class);
        intent.putExtra("title", title);
        return intent;
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);

        setBarTitleTx(getIntent().getStringExtra("title"));

        mAdapter = new DownloadManagerAdapter(mContext, mDataMap, this);
        downloadListview.setAdapter(mAdapter);
        downloadListview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;//返回true,表示不可点击
            }
        });

        checkData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAdapter!=null) {
            checkData();
        }
    }

    private void checkData() {
        mDataMap.clear();
        unPlayDataList.clear();
        playDataList.clear();

        List<DownLoadModel> tempList = DownloadManager.getInstance().getnotFinishDownload();
        if (tempList!=null && tempList.size()>0) {
            unPlayDataList.addAll(tempList);
            mDataMap.add(unPlayDataList);
        }

        List<DownLoadModel> tempList2 = DownloadManager.getInstance().getAllFinishDownload();
        if (tempList2!=null && tempList2.size()>0) {
            playDataList.addAll(tempList2);
            mDataMap.add(playDataList);
        }
        mAdapter.notifyDataSetChanged();
        //设置列表默认全部展开
        for (int i = 0; i < mAdapter.getGroupCount(); i++) {
            downloadListview.expandGroup(i);
        }
    }

    @Override
    public void onUserEvent(DownloadResultEvent eventData) {
        super.onUserEvent(eventData);
        LogUtils.e("tbl>>>>>:"+eventData.status);
        changeStatus(eventData.url, eventData.status);
        switch (eventData.status) {
            case CommonDownloadTask.STATUS_START:
                break;
            case CommonDownloadTask.STATUS_PROGRESS:
                for (int j=0;j<mDataMap.size();j++) {
                    for (int i=0;i<mDataMap.get(j).size();i++) {
                        if (mDataMap.get(j).get(i).getDownloadUrl().equals(eventData.url)) {
                            mDataMap.get(j).get(i).setProgress(eventData.progress);
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
                break;
            case CommonDownloadTask.STATUS_STOP:
                break;
            case CommonDownloadTask.STATUS_ERROR:
                checkData();
                break;
            case CommonDownloadTask.STATUS_FINISH:
                checkData();
                break;
            case CommonDownloadTask.STATUS_ZIP_FAIL:
                checkData();
                break;
            case CommonDownloadTask.STATUS_STSRT_ZIP:
                checkData();
                break;
            case CommonDownloadTask.STATUS_ZIP_PROGRESS:
                for (int j=0;j<mDataMap.size();j++) {
                    for (int i=0;i<mDataMap.get(j).size();i++) {
                        if (mDataMap.get(j).get(i).getDownloadUrl().equals(eventData.url)) {
                            mDataMap.get(j).get(i).setProgress(eventData.progress);
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
                checkData();
                break;
        }
    }

    private void changeStatus(String url, int statusProgress) {
        for (int i=0;i<playDataList.size();i++) {
            if (playDataList.get(i).getDownloadUrl().equals(url)) {
                playDataList.get(i).setStatus(statusProgress);
                mAdapter.notifyDataSetChanged();
                break;
            }
        }
        DownloadManager.getInstance().updataDownload(playDataList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void download(DownLoadModel start) {
        try {
            factory.addTask(new CommonDownloadTask(start.getDownloadUrl()
                    , start.getGameZipName()
                    , start.getDownloadDir()
                    , start.getGameName()));
        } catch (Exception e) {
            showToast(e.getMessage());
        }
    }

    @Override
    public void onAdapterItemGroupClick(View view, int groupPosition) {
        wranDialog(R.string.dialog_delete_content, true, "");
    }

    MyDialog mDialog = null;
    private void wranDialog(int resId, final boolean isAll, final String url) {
        mDialog = new MyDialog(this, R.style.MyDialog);
        mDialog.setContentView(R.layout.bind_dialog);

        Button dialog_button_cancel = (Button) mDialog.findViewById(R.id.dialog_button_cancel);
        Button dialog_button_ok = (Button) mDialog.findViewById(R.id.dialog_button_ok);
        TextView tip_title = (TextView) mDialog.findViewById(R.id.tip_title);
        TextView dialog_content = (TextView) mDialog.findViewById(R.id.dialog_content);
        TextView dialog_desci = (TextView) mDialog.findViewById(R.id.dialog_desci);

        tip_title.setText(getResources().getString(R.string.dialog_title));
        dialog_content.setText(getResources().getString(resId));
        dialog_desci.setVisibility(View.GONE);
        dialog_button_cancel.setText(getResources().getString(R.string.dialog_ok));
        dialog_button_ok.setText(getResources().getString(R.string.dialog_cancle));

        dialog_button_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogDismiss();
                if (isAll) {
                    DownloadManager.getInstance().deleteAllFinishDownload();
                } else {
                    DownloadManager.getInstance().deleteDownload(url);
                }
                new Handler().postAtTime(new Runnable() {
                    @Override
                    public void run() {
                        checkData();
                    }
                }, 200);
            }
        });
        dialog_button_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogDismiss();
            }
        });
        if (null != mDialog) {
            if (mDialog.isShowing()) return;
            mDialog.show();
        }
    }

    private void dialogDismiss() {
        if (null != mDialog && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onAdapterItemChildClick(View view, int groupPosition, int childPosition) {
        DownLoadModel start = mAdapter.getChild(groupPosition, childPosition);
        switch (start.getStatus()) {
            case CommonDownloadTask.STATUS_ERROR:
                File file = new File(start.getDownloadDir()+start.getGameZipName());
                if (file.exists())
                    FileUtils.deleteFile(file);
                File file2 = new File(start.getGamePath());
                if (file2.exists())
                    FileUtils.deleteFile(file2);
                download(start);
                break;
            case CommonDownloadTask.STATUS_START:
            case CommonDownloadTask.STATUS_STOP:
                download(start);
                break;
            case CommonDownloadTask.STATUS_PROGRESS:
                if (factory.isExitTask(start.getDownloadUrl()))
                    factory.cancelTask(start.getDownloadUrl());
                else
                    download(start);
                break;
            case CommonDownloadTask.STATUS_FINISH:
                StartGame(start.getDownloadUrl(), start.getGamePath()+"/"+start.getGameZipName().replace(".zip",""));
                break;
            case CommonDownloadTask.STATUS_ZIP_FAIL:
                download(start);
                break;
            case CommonDownloadTask.STATUS_STSRT_ZIP:
            case CommonDownloadTask.STATUS_ZIP_PROGRESS:
                break;
            default:
                download(start);
                break;
        }
    }

    @Override
    public void onAdapterItemLongChildClick(View view, int groupPosition, int childPosition) {
        DownLoadModel start = mAdapter.getChild(groupPosition, childPosition);
        wranDialog(R.string.dialog_single_delete_content, false, start.getDownloadUrl());
    }

    /**
     * 防止快速点击,启动多个同样的界面
     *
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            } else {
                lastClickTime = now;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 防止快速点击,启动多个同样的界面
     *
     * @return
     */
    public boolean isFastDoubleClick() {
        now = System.currentTimeMillis();
        long timeD = now - lastClickTime;
//        lastClickTime = now;
        return timeD <= 1000;
    }
}
